package aip.ui.user.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import aip.core.dao.information.CatalogDao;
import aip.core.model.user.User;
import aip.ui.user.srvc.AuthenticationService;

public class AuthenticationFilter implements Filter
{
    private AuthenticationService authenticationService;

    public void destroy()
    {
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException
    {
        boolean continues = true;
        try
        {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            HttpSession seesion = request.getSession();
            this.initService(request);
            request.setAttribute("menuList", CatalogDao.menuList);
            request.setAttribute("catalogMap", CatalogDao.catalogMap);
            request.setAttribute("allCatalog", CatalogDao.allCatalog);
            request.setAttribute("longCatalog", CatalogDao.longCatalog);
            request.setAttribute("contextPath", request.getContextPath());

            // 判断uri是否是登陆或者退出
            String uri = request.getRequestURI();
            int pathParamIndex = uri.indexOf(';');
            if (pathParamIndex > 0)
            {
                uri = uri.substring(0, pathParamIndex);
            }
            if (StringUtils.hasText(uri))
            {
                if (uri.endsWith(request.getContextPath()
                        + this.authenticationService.getLoginUrl()))
                {
                    // 验证码
                    String verifycode = request.getParameter("verifycode");
                    String correctVCode = String.valueOf(request.getSession()
                            .getAttribute("verifyCode"));
                    if (!verifycode.equalsIgnoreCase(correctVCode))
                    {
                        continues = false;
                    }
                    // 登陆
                    String username = request.getParameter("username");
                    String password = request.getParameter("password");
                    User user = this.authenticationService.getValidUser(
                            username, password);
                    if (user != null)
                    {
                        seesion.setAttribute(
                                CurrentUserInitializeFilter.SESSION_USER_HOLDER,
                                user);
                        UserHelper.setUser(user);
                        continues = false;
                        response.sendRedirect(request.getContextPath()
                                + this.authenticationService.getSuccessUrl());
                    }
                    else
                    {
                        response.sendRedirect(request.getContextPath()
                                + this.authenticationService.getFaildUrl());
                        continues = false;
                    }
                }
                else if (uri.endsWith(request.getContextPath()
                        + this.authenticationService.getLogoutUrl()))
                {
                    // 退出
                    seesion = request.getSession();
                    seesion.removeAttribute(CurrentUserInitializeFilter.SESSION_USER_HOLDER);
                    UserHelper.setUser(null);
                    response.sendRedirect(request.getContextPath()
                            + this.authenticationService.getUserLoginUrl());
                    continues = false;
                }
                uri = uri.replace(request.getContextPath(), "");
                // 未登陆用户
                boolean isHeist = UserHelper.getUser() == null
                        && this.authenticationService.getFilterUrl().get(uri) == null ? false
                        : true;
                if (UserHelper.getUser() != null)
                {
                    String userType = UserHelper.getUser().getType();
                    if ("admin".equals(userType))
                    {
                        isHeist = this.authenticationService.getAdminUrl().get(
                                uri) == null ? false : true;
                    }
                    else if ("expert".equals(userType))
                    {
                        isHeist = this.authenticationService.getExpertUrl()
                                .get(uri) == null ? false : true;
                    }
                    else if ("service".equals(userType))
                    {
                        isHeist = this.authenticationService.getServiceUrl()
                                .get(uri) == null ? false : true;
                    }
                    else if ("company".equals(userType))
                    {
                        isHeist = this.authenticationService.getCompanyUrl()
                                .get(uri) == null ? false : true;
                    }
                }
                if (isHeist)
                {
                    response.sendRedirect(request.getContextPath()
                            + this.authenticationService.getUserLoginUrl());
                    continues = false;
                }

            }
        }
        finally
        {
            if (continues)
            {
                chain.doFilter(req, resp);
            }
        }

    }

    private void initService(HttpServletRequest request)
    {
        if (this.authenticationService == null)
        {
            ApplicationContext context = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(request.getSession()
                            .getServletContext());
            this.authenticationService = (AuthenticationService) context
                    .getBean("authenticationService");
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException
    {
        // do nothing
    }

}
